onload = () => {
    loadCSS("../css/fontello.css", "bootstrap5-icon");
    loadCSS("../css/bootstrap5.min.css", "bootstrap5");
    loadScript("../js/bootstrap5.bundle.min.js").then(() => loadScript("../js/crud.js")).then(() => {
        let accountOperator = new Crud({
            module: "account",
            hasCheckbox: true,
            initForm: {
                "#editContainer": [
                    {name: "loginName", "required": "required"},
                    {
                        caption: "User",
                        "name": "relatedUser",
                        "required": "required",
                        type: "combo",
                        iterator: "user.list"

                    }]
            },
            iterators: [{
                name: "user.no_account", type: "noAccountUser", convert: u => {
                    return {value: u.userId, "caption": u.userName}
                }
            },{
                name: "user.list", type: "users", convert: u => {
                    return {value: u.userId, "caption": u.userName}
                }
            }],
            extendAttribute: [{name: "relatedUser", type: "userById"}
            ],
            opsButton: ["new"],
            search: [{caption: "Name", "type": "text", "name": "loginName", class: "col-3"}],
            listField: [{"caption": "ID", "field": "accountId"},
                {"caption": "Login Name", "field": "loginName"},
                {"caption": "User Name", "field": "relatedUser_userById.userName"}],
            rowBtn: ["edit", "delete",
                {
                    "caption": "icon-icon-pencil", "class": "btn-warning",
                    action:"modal",
                    param:"#editModal",
                    callback: (e, b, c, d) => {
                        e.stopPropagation();
                        const id = b.accountId;
                        ajax(`/account/get?accountId=${id}`, {}, function (data) {
                            let dataForm = document.getElementById("editModal").querySelector("form");
                            const elements = dataForm.elements;
                            const groupedElements = {};
                            for (let element of elements) {
                                if (element.name) {
                                    if (!groupedElements[element.name]) {
                                        groupedElements[element.name] = [];
                                    }
                                    groupedElements[element.name].push(element);
                                }
                            }
                            Object.keys(groupedElements).forEach(group => {
                                let input = groupedElements[group];
                                input && input.length > 0 && (input[0].value = data.data[group])
                            });
                        });
                    }, "commit": (form, env) => {
                        const data = {};
                        data.accountId = form.elements["accountId"].value;
                        data.loginName = form.elements["loginName"].value;
                        data.relatedUser = form.elements["relatedUser"].value;
                        ajax("/account/update/related", {method:"POST", body: data});
                    }
                },
                {
                    caption: "Reset Password",
                    "class": "btn btn-primary",
                    callback: (a, item, c, d) => {
                        let password = prompt("Please input password");
                        if (password) {
                            ajax(`/account/change/password?accountId=${item.accountId}&password=${password}`, {}, (data) => {
                                showToast(`${data.message}<br/>${JSON.stringify(data.data ?? [])}`, "primary")
                            }, (error) => showToast("Change password fail:[] caused by:" + error));
                        }
                    }
                }],
            editFields: [
                {name: "loginName", "required": "required"},
                {
                    caption: "User",
                    "name": "relatedUser",
                    "required": "required",
                    type: "combo",
                    iterator: "user.no_account"
                }, {
                    caption: "Init Password",
                    "name": "password",
                    "required": "required",
                    type: "password",
                    iterator: "user.no_account"
                }
            ]
        });
        accountOperator.init()
    }).catch((err) => console.error(err));
}
